const {
  contextBridge,
  ipcRenderer
} = require('electron');

const validChannels = ['get-printers', 'return-printers', 'xmf-print', 'xmf-print-pdf', 'node-server'];

var notifyWaitFiles

contextBridge.exposeInMainWorld('electron', {
  files: {
    onWait: (nwf) => {
      notifyWaitFiles = nwf
    }
  },
  ipcRenderer: {
    send: (channel, data) => {
      // whitelist channels To Main Process
      if (validChannels.includes(channel)) {
        ipcRenderer.send(channel, data);
      }
    },
    receive: (channel, func) => {
      // From Main Process
      if (validChannels.includes(channel)) {
        ipcRenderer.on(channel, (event, ...args) => func(...args));
      }
    },
    once: (channel, func) => {
      // From Main Process
      if (validChannels.includes(channel)) {
        ipcRenderer.once(channel, (event, ...args) => func(...args));
      }
    }
  },
});

const http = require('http');

const hostname = 'localhost'
const port = 10027

var waitPrintFiles = []

const addPrintFile = (file) => {
  waitPrintFiles.push(file)
  if (notifyWaitFiles) {
    notifyWaitFiles(waitPrintFiles)
  }
}

const removePrintFile = () => {
  if (waitPrintFiles.length > 0) {
    waitPrintFiles.shift()
    if (notifyWaitFiles) {
      notifyWaitFiles(waitPrintFiles)
    }
  }
}

const server = http.createServer((req, res) => {

  const {
    method,
    headers
  } = req

  const contentType = headers['content-type']

  if ('GET' === method) {
    res.statusCode = 405
    res.end('Method not support')
  }

  if ('POST' === method) {

    if ('application/json' !== contentType) {
      res.end('Not support Content-Type')
      return
    }

    let data = ''
    req.on('data', (postdate) => {
      data += postdate
    })

    let params
    req.on('end', () => {
      data = decodeURI(data)
      params = JSON.parse(data)
      // ipcRenderer.send('node-server', 'node server process');
      const {
        file
      } = params
      if (!file) {
        let result = {
          success: false,
          message: 'parameter file required'
        }
        res.end(JSON.stringify(result))
      } else {
        addPrintFile({
          image: file,
          createTime: getTime()
        })
        let result = {
          success: true,
        }
        res.end(JSON.stringify(result))
      }
    })

    res.statusCode = 200
    res.setHeader('Content-Type', 'application/json')
  }
})

server.on('clientError', (err, socket) => {
  socket.end('HTTP/1.1 400 Bad Request');
})

server.on('close', () => {
  console.log('server close')
})

server.on('connection', () => {})

server.on('error', (error) => {})

server.listen(port, hostname, () => {
  console.log(`Server listen on http://${hostname}:${port}`);
})

function getTime() {
  var myDate = new Date();
  var myYear = myDate.getFullYear(); //获取完整的年份(4位,1970-????)
  var myMonth = myDate.getMonth() + 1; //获取当前月份(0-11,0代表1月)
  var myToday = myDate.getDate(); //获取当前日(1-31)
  var myDay = myDate.getDay(); //获取当前星期X(0-6,0代表星期天)
  var myHour = myDate.getHours(); //获取当前小时数(0-23)
  var myMinute = myDate.getMinutes(); //获取当前分钟数(0-59)
  var mySecond = myDate.getSeconds(); //获取当前秒数(0-59)
  var nowTime;

  nowTime = myYear + '.' + fillZero(myMonth) + '.' + fillZero(myToday) + ' ' + fillZero(myHour) + ':' +
    fillZero(myMinute) + ':' + fillZero(mySecond);

  return nowTime
};

function fillZero(str) {
  var realNum;
  if (str < 10) {
    realNum = '0' + str;
  } else {
    realNum = str;
  }
  return realNum;
}
